package other.system.client.fssc;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.api.annotations.RequestMethod;
import com.rkhd.platform.sdk.api.annotations.RestApi;
import com.rkhd.platform.sdk.api.annotations.RestMapping;
import com.rkhd.platform.sdk.api.annotations.RestQueryParam;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEvent;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventRequest;
import com.rkhd.platform.sdk.creekflow.approvalevent.ApprovalEventResponse;
import com.rkhd.platform.sdk.data.model.Account;
import com.rkhd.platform.sdk.data.model.Contract;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.trigger.DataResult;
import com.rkhd.platform.sdk.trigger.Trigger;
import com.rkhd.platform.sdk.trigger.TriggerRequest;
import com.rkhd.platform.sdk.trigger.TriggerResponse;
import org.apache.commons.lang.StringUtils;
import other.system.client.apitool.FsscClientUtils;
import other.system.client.util.HCDateUtils;
import other.system.client.util.HCXObjectService;
import other.system.client.util.ResultBody;
import other.system.client.util.TfReturnMsgTools;

import java.util.*;

/**
 * @Description: FSSC 合同审批通过，推送客户数据到FSSC
 * @Author: 黎炎松
 * @Date: 2024/6/19 16:23
 */
@RestApi(baseUrl = "/xsy/fssc")
public class ContractCompleteSendFssc implements ApprovalEvent, Trigger {
    private static HCXObjectService hcxObjectService = new HCXObjectService();
    private static final Logger logger = LoggerFactory.getLogger();
    private static String LOGGER_MSG = "推送客户数据到FSSC ==> ";

    /**
     * trigger 触发事件
     * @param request
     * @return
     * @throws ScriptBusinessException
     */
    @Override
    public TriggerResponse execute(TriggerRequest request) throws ScriptBusinessException {
        logger.info(LOGGER_MSG + " 触发开始 ");
        List<XObject> dataList = request.getDataList();
        List<DataResult> dataResultList = new ArrayList<>();
        List<XObject> objectList = new ArrayList<>();
        for (XObject xObject : dataList) {
            objectList.add(xObject);
            dataResultList.add(new DataResult(true, "", xObject));
        }

        // 1.OA审批状态为通过 2.签约客户名称进行变更
        Contract contract = (Contract) objectList.get(0);
        Integer oaApprovalStatus = contract.getOaApprovalStatus__c();
        if (oaApprovalStatus != 5) {
            return new TriggerResponse(true, "处理完成", dataResultList);
        }

        try {
            // 判断是否推送客户
            Contract oldContract = new Contract();
            oldContract.setId(contract.getId());
            oldContract = hcxObjectService.get(oldContract);
            logger.info(LOGGER_MSG + "签约客户 = " + contract.getClientName__c());
            logger.info(LOGGER_MSG + "旧的签约客户 = " + contract.getClientName__c());
            if (!Objects.equals(contract.getClientName__c(), oldContract.getClientName__c())) {
                syncAccountData(contract.getClientName__c());
            }
        } catch (ApiEntityServiceException e) {
            e.printStackTrace();
        }
        return new TriggerResponse(true, "处理完成", dataResultList);
    }

    /**
     * 审批触发事件
     * @param request
     * @return
     */
    @Override
    public ApprovalEventResponse execute(ApprovalEventRequest request) {
        logger.info(LOGGER_MSG + "触发开始");
        logger.info("ObjectApiKey:" + request.getEntityApiKey() + " , DataId:" + request.getDataId());

        // 自动同步：合同审批通过后把【客户名称（最终用户）】 accountId 、【签约客户名称】 clientName__c（当两者一样时只传【客户名称（最终用户）】）自动同步；
        try {
            Contract contract = new Contract();
            contract.setId(request.getDataId());
            contract = hcxObjectService.get(contract);

            // 推送客户
            Long accountId = contract.getAccountId();
            logger.info(LOGGER_MSG + "推送客户 accountId = " + accountId);
            syncAccountData(accountId);


            // 判断是否一致 不一致推送签约客户
            Long clientNameId = contract.getClientName__c();
            logger.info(LOGGER_MSG + "推送客户 clientNameId = " + clientNameId);
            if (!Objects.equals(accountId, clientNameId)) {
                logger.info(LOGGER_MSG + "推送签约客户");
                syncAccountData(clientNameId);
            }

        } catch (ApiEntityServiceException e) {
            throw new RuntimeException(e);
        }

        ApprovalEventResponse response = new ApprovalEventResponse();
        response.setSuccess(true);
        response.setMsg("success");
        return response;
    }

    /**
     * 手动推送客户数据
     * @param accountId
     * @return
     */
    @RestMapping(value = "/syncAccount", method = RequestMethod.POST)
    public String syncAccount(@RestQueryParam(name = "id") Long accountId) throws ApiEntityServiceException {
        logger.info(LOGGER_MSG + "执行了按钮事件 = " + accountId);
        return syncAccountData(accountId);
    }

    public static void main(String[] args) throws ApiEntityServiceException {
        ContractCompleteSendFssc contractCompleteSendFssc = new ContractCompleteSendFssc();
        contractCompleteSendFssc.syncAccountData(3548062220819056L);
    }

    /**
     * 推送客户数据到Fssc
     * @param accountId
     * @return
     */
    public String syncAccountData(Long accountId) {
        try {
            // 获取用户数据
            Account account = new Account();
            account.setId(accountId);
            account = hcxObjectService.get(account);
            logger.info(LOGGER_MSG + "处理开始: " + account);

            // 纳税登记号不可为空
            String taxRegistrationNo = account.getTaxRegistrationNo__c();
            if (StringUtils.isBlank(taxRegistrationNo)) {
                logger.info(LOGGER_MSG + "纳税登记号不可为空");
                return TfReturnMsgTools.getFailResult("纳税登记号不可为空");
            }

            // 拼接发送参数
            Map<String, String> fsscConfig = FsscClientUtils.fsscConfig;
            logger.info(LOGGER_MSG + "fsscConfig: " + fsscConfig);
            JSONObject sendData = new JSONObject();
            sendData.put("id", account.getId());
            sendData.put("name", account.getAccountName());
            sendData.put("taxNum", taxRegistrationNo);
            setDefaultData(sendData, fsscConfig, account);

            String timeStr = HCDateUtils.dateToString(new Date(), HCDateUtils.FORMATTIME); // 时间字符串
            long uiquekey = account.getId(); // 数据唯一值

            JSONObject reqBody = new JSONObject();
            reqBody.put("data", sendData);
            reqBody.put("timestamp", timeStr);
            reqBody.put("randomstr", uiquekey);
            reqBody.put("uiquekey", uiquekey);
            reqBody.put("source", fsscConfig.getOrDefault("source", "KHJK007"));
            logger.info(LOGGER_MSG + "发送的数据: " + reqBody);

            // 推送到第三方
            ResultBody resultBody = FsscClientUtils.sendPost(reqBody, FsscClientUtils.ADD_UP_ACCOUNT_URL);
            logger.info(LOGGER_MSG + "resultBody:" + resultBody);
            if (!Objects.equals(resultBody.getCode(), "200")) {
                logger.info(LOGGER_MSG + "推送异常: " + resultBody.getMessage());
                return TfReturnMsgTools.getFailResult("推送异常:" + resultBody.getMessage());
            }

            logger.info(LOGGER_MSG + "推送成功: " + account.getAccountName());
            return TfReturnMsgTools.getSuccessResult("推送成功");
        } catch (Exception e) {
            logger.info(LOGGER_MSG + "处理异常: " + e.getMessage());
            return TfReturnMsgTools.getFailResult("推送异常:" + e.getMessage());
        }
    }


    /**
     * 设置发送的默认数据
     *
     * @param sendData
     * @param account
     */
    public void setDefaultData(JSONObject sendData, Map<String, String> fsscConfig, Account account) {
        sendData.put("reqUser", fsscConfig.getOrDefault("reqUser", "kty.finance.bss")); // 申请人
        sendData.put("reqDept", fsscConfig.getOrDefault("reqDept", "A00094102")); // 部门

        // 是否TCL体系 1:是 2:否   是: Z110 否: Z010
        Integer tclSystem = account.getTclSystem__c();
        sendData.put("accountGroup", tclSystem == 1 ? "Z110" : "Z010"); // 客户账户组

        // 公司列表
        String tempCompanyStr = "[{\"companyCode\":\"L410\",\"account\":\"1122010301\",\"clearAccount\":\"\",\"manageGroup\":\"\",\"memo\":\"\"}," +
                "{\"companyCode\":\"L409\",\"account\":\"1122010301\",\"clearAccount\":\"\",\"manageGroup\":\"\",\"memo\":\"\"}," +
                "{\"companyCode\":\"L405\",\"account\":\"1122010301\",\"clearAccount\":\"\",\"manageGroup\":\"\",\"memo\":\"\"}," +
                "{\"companyCode\":\"L400\",\"account\":\"1122010301\",\"clearAccount\":\"\",\"manageGroup\":\"\",\"memo\":\"\"}," +
                "{\"companyCode\":\"2013\",\"account\":\"1122010301\",\"clearAccount\":\"\",\"manageGroup\":\"\",\"memo\":\"\"}]";
        String companyListStr = fsscConfig.getOrDefault("companyList", tempCompanyStr);
        sendData.put("companyList", JSONArray.parseArray(companyListStr));

        // 销售视图
        String tempSaleStr = "[{\"salesOrganization\":\"L410\",\"distributionChannel\":\"00\",\"division\":\"D0\",\"salesDistrict\":\"\",\"salesOffice\":\"L001\",\"salesGroup\":\"\",\"marketLevel\":\"\",\"levelChannel1\":\"\",\"levelChannel2\":\"\",\"levelChannel3\":\"\",\"billToParty\":\"\",\"superiorAgent\":\"\",\"payer\":\"\",\"termsofpayment\":\"\",\"acctassgmtgroup\":\"\",\"incoTerm1\":\"\",\"incoTerm2\":\"\",\"taxes\":\"1\",\"currency\":\"\",\"salesMan\":\"\",\"factory\":\"\",\"priceGroup\":\"\",\"custPriceProcess\":\"1\",\"shipment\":\"\",\"priceList\":\"\"}," +
                "{\"salesOrganization\":\"L409\",\"distributionChannel\":\"00\",\"division\":\"D0\",\"salesDistrict\":\"\",\"salesOffice\":\"L001\",\"salesGroup\":\"\",\"marketLevel\":\"\",\"levelChannel1\":\"\",\"levelChannel2\":\"\",\"levelChannel3\":\"\",\"billToParty\":\"\",\"superiorAgent\":\"\",\"payer\":\"\",\"termsofpayment\":\"\",\"acctassgmtgroup\":\"\",\"incoTerm1\":\"\",\"incoTerm2\":\"\",\"taxes\":\"1\",\"currency\":\"\",\"salesMan\":\"\",\"factory\":\"\",\"priceGroup\":\"\",\"custPriceProcess\":\"1\",\"shipment\":\"\",\"priceList\":\"\"}," +
                "{\"salesOrganization\":\"L405\",\"distributionChannel\":\"00\",\"division\":\"D0\",\"salesDistrict\":\"\",\"salesOffice\":\"L001\",\"salesGroup\":\"\",\"marketLevel\":\"\",\"levelChannel1\":\"\",\"levelChannel2\":\"\",\"levelChannel3\":\"\",\"billToParty\":\"\",\"superiorAgent\":\"\",\"payer\":\"\",\"termsofpayment\":\"\",\"acctassgmtgroup\":\"\",\"incoTerm1\":\"\",\"incoTerm2\":\"\",\"taxes\":\"1\",\"currency\":\"\",\"salesMan\":\"\",\"factory\":\"\",\"priceGroup\":\"\",\"custPriceProcess\":\"1\",\"shipment\":\"\",\"priceList\":\"\"}," +
                "{\"salesOrganization\":\"L400\",\"distributionChannel\":\"00\",\"division\":\"D0\",\"salesDistrict\":\"\",\"salesOffice\":\"L001\",\"salesGroup\":\"\",\"marketLevel\":\"\",\"levelChannel1\":\"\",\"levelChannel2\":\"\",\"levelChannel3\":\"\",\"billToParty\":\"\",\"superiorAgent\":\"\",\"payer\":\"\",\"termsofpayment\":\"\",\"acctassgmtgroup\":\"\",\"incoTerm1\":\"\",\"incoTerm2\":\"\",\"taxes\":\"1\",\"currency\":\"\",\"salesMan\":\"\",\"factory\":\"\",\"priceGroup\":\"\",\"custPriceProcess\":\"1\",\"shipment\":\"\",\"priceList\":\"\"}," +
                "{\"salesOrganization\":\"2013\",\"distributionChannel\":\"00\",\"division\":\"D0\",\"salesDistrict\":\"\",\"salesOffice\":\"L001\",\"salesGroup\":\"\",\"marketLevel\":\"\",\"levelChannel1\":\"\",\"levelChannel2\":\"\",\"levelChannel3\":\"\",\"billToParty\":\"\",\"superiorAgent\":\"\",\"payer\":\"\",\"termsofpayment\":\"\",\"acctassgmtgroup\":\"\",\"incoTerm1\":\"\",\"incoTerm2\":\"\",\"taxes\":\"1\",\"currency\":\"\",\"salesMan\":\"\",\"factory\":\"\",\"priceGroup\":\"\",\"custPriceProcess\":\"1\",\"shipment\":\"\",\"priceList\":\"\"}]";
        String saleListStr = fsscConfig.getOrDefault("saleList", tempSaleStr) ;
        List<JSONObject> saleList = JSONArray.parseArray(saleListStr, JSONObject.class);
        // 是否TCL体系为是 -Z110、acctassgmtgroup：01，是否TCL体系为否 -Z010、acctassgmtgroup：02，currency 按客户实际传，人民币传CNY，欧元传EUR，美元传USD，新加坡元传SGD，马来西亚林吉特传MYR 。
        for (JSONObject sale : saleList) {
            sale.put("acctassgmtgroup", tclSystem == 1 ? "01" : "02");
        }
        sendData.put("saleList", saleList);
    }


}
